//
//  BCColorBoard.m
//  图片编辑
//
//  Created by aaaa on 2020/3/24.
//  Copyright © 2020 aaaa. All rights reserved.
//

#import "BCColorBoard.h"
#import "BCColorItemLayer.h"

#define Border_Padding UIEdgeInsetsMake(32, 13, 25, 13) //整个气泡的内边距
static const int Item_Length = 18; //格子的边长
static const int Item_margin = 5; //格子之间的间距
static const int row = 6;
static const int colume = 8;

@interface BCColorBoard ()
@property(nonatomic,strong)CALayer *selectedColorLayer;
@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)NSMutableArray<BCColorItemLayer *> *colorItems;
@end
@implementation BCColorBoard
{
    CGRect _colorZoonRect;
    BCColorItemLayer *_selectedLayer;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        self.hidden = YES;
        self.alpha = 0;
        self.image = [UIImage imageNamed:@"img_colorboard_backgroud"];
        self.userInteractionEnabled = YES;
        [self cuculateSelfSize];
        [self initUI];
    }
    return self;
}

//计算自己的大小
-(void)cuculateSelfSize{
    
    int total_item_margin_horizontal = (colume - 1) * Item_margin;
    int total_item_margin_vertical   = (row - 1) * Item_margin;
    
    int color_zone_height = total_item_margin_vertical + row * Item_Length;
    int color_zone_width  = total_item_margin_horizontal + colume * Item_Length;
            
    int width  = color_zone_width  + Border_Padding.left + Border_Padding.right;
    int height = color_zone_height + Border_Padding.top + Border_Padding.bottom;
    
    self.frame = (CGRect){CGPointZero,CGSizeMake(width, height)};
    
    //颜色区域的四周多出 间距的一半 以便于计算 这样每个格子的有效区域 等于变长+间距
    _colorZoonRect = CGRectMake(Border_Padding.left - Item_margin * .5,
                                Border_Padding.top - Item_margin * .5,
                                self.frame.size.width - Border_Padding.left - Border_Padding.right + Item_margin,
                                self.frame.size.height - Border_Padding.top - Border_Padding.bottom + Item_margin);
}

-(void)initUI{
    //标题
    _titleLabel = [self titleLabel];
    _titleLabel.textColor = [UIColor blackColor];
    _titleLabel.frame = (CGRect){CGPointMake(Border_Padding.left, 0),CGSizeMake(self.frame.size.width - Border_Padding.left, Border_Padding.top)};
    [self addSubview:_titleLabel];
    
    
    //颜色块
    CGFloat start_x = Border_Padding.left;
    CGFloat stary_y = Border_Padding.top;
    
    _colorItems = @[].mutableCopy;
    
    for (int i = 0; i < [self colorArray].count; i++) {
        
        CGFloat currentRow = i / colume ;
        CGFloat currentColume = i % colume;
        
        CGFloat x = currentColume * (Item_Length + Item_margin);
        CGFloat y = currentRow * (Item_Length + Item_margin);
        
        x+= start_x;
        y+= stary_y;
        
        CGRect frame = (CGRect){CGPointMake(x, y),CGSizeMake(Item_Length, Item_Length)};
        
        BCColorItemLayer *layer = [[BCColorItemLayer alloc]initWithFrame:frame backGroudColor:[self colorArray][i].CGColor];
        [self.layer addSublayer:layer];
        
        [_colorItems addObject:layer];
    }
    
    //选中的颜色块
    _selectedColorLayer = [self selectedColorLayer];
    _selectedColorLayer.frame = (CGRect){ CGPointMake(self.frame.size.width - Border_Padding.right - Item_Length, 7),CGSizeMake(Item_Length, Item_Length)};
    [self.layer addSublayer:self.selectedColorLayer];
}


//从某个点弹出
-(void)showAtPosition:(CGPoint)position{
    self.hidden = NO;
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    // 设置右上角为transform的起点（默认是中心点）
    self.layer.position = CGPointMake(position.x + 35, position.y - 5);
    // 向右下transform
    self.layer.anchorPoint = CGPointMake(1, 0.96);
    self.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 1;
        self.transform = CGAffineTransformMakeScale(1.0, 1.0);
    }];
    
}

//消失
-(void)disappear{
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 0;
        self.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}

-(BOOL)isShowing{
    return self.alpha == 1.0;
}

#pragma mark - gesture - 这里的点击和滑动 要把格子的间距算进去 比如间距是3 那么有效范围就是图片的宽高+周围的一半边距
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    [self locateChossenLayerAtPosition:point];
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    [self locateChossenLayerAtPosition:point];
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    [self locateChossenLayerAtPosition:point];
    
    if (_selectedLayer) {
        [_selectedLayer setIsHightLight:NO];
        [self disappear];
    }
    NSLog(@"%@",_selectedLayer);
}

-(void)locateChossenLayerAtPosition:(CGPoint)position{
    
    if (CGRectContainsPoint(_colorZoonRect, position)) {
        
        //为扩大有效点击范围 格子的有效范围 向四周扩大一半的间距 即横向纵向的距离都加上间距
        int select_colume = (position.x - _colorZoonRect.origin.x) / (Item_Length + Item_margin);
        int select_row = (position.y - _colorZoonRect.origin.y) / (Item_Length + Item_margin);
        
        int index = select_row * colume + select_colume;
        
        if (_selectedLayer == self.colorItems[index]) {
            [_selectedLayer setIsHightLight:YES];
        }else{
            [_selectedLayer setIsHightLight:NO];
            _selectedLayer = self.colorItems[index];
            [_selectedLayer setIsHightLight:YES];
        }
        
        _selectedColorLayer.backgroundColor = [_selectedLayer getColor].CGColor;
        NSLog(@"row = %d colume = %d",row,colume);
        !_didselectColor ? : _didselectColor([self colorArray][index]);
    }else{
        if (_selectedLayer) {
            _selectedColorLayer.backgroundColor = [UIColor clearColor].CGColor;
            _selectedLayer.isHightLight = NO;
            _selectedLayer = nil;
        }
    }
}

#pragma mark - getter -
-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel new];
        _titleLabel.font = [UIFont systemFontOfSize:14.5];
        _titleLabel.text = @"选取颜色";
    }
    return _titleLabel;
}

-(NSArray<UIColor *> *)colorArray{
    static NSArray<UIColor *> *colorArray;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        colorArray = @[RGB_COLOR(249, 235, 234),
        RGB_COLOR(245, 238, 248),
        RGB_COLOR(234, 242, 248),
        RGB_COLOR(209, 242, 235),
        RGB_COLOR(252, 243, 207),
        RGB_COLOR(253, 242, 233),
        RGB_COLOR(246, 221, 204),
        RGB_COLOR(235, 237, 239),
        RGB_COLOR(241, 148, 138),
        RGB_COLOR(187, 143, 206),
        RGB_COLOR(174, 214, 241),
        RGB_COLOR(163, 228, 215),
        RGB_COLOR(247, 220, 111),
        RGB_COLOR(240, 178, 122),
        RGB_COLOR(229, 152, 102),
        RGB_COLOR(174, 182, 191),
        RGB_COLOR(231, 76, 60),
        RGB_COLOR(142, 68, 173),
        RGB_COLOR(93, 173, 226),
        RGB_COLOR(26, 188, 156),
        RGB_COLOR(244, 208, 63),
        RGB_COLOR(230, 126, 34),
        RGB_COLOR(220, 118, 51),
        RGB_COLOR(52, 73, 94),
        RGB_COLOR(176, 58, 46),
        RGB_COLOR(125, 60, 152),
        RGB_COLOR(46, 134, 193),
        RGB_COLOR(23, 165, 137),
        RGB_COLOR(212, 172, 13),
        RGB_COLOR(175, 96, 26),
        RGB_COLOR(186, 74, 0),
        RGB_COLOR(46, 64, 83),
        RGB_COLOR(148, 49, 38),
        RGB_COLOR(108, 52, 131),
        RGB_COLOR(33, 97, 140),
        RGB_COLOR(17, 120, 100),
        RGB_COLOR(154, 125, 10),
        RGB_COLOR(147, 81, 22),
        RGB_COLOR(135, 54, 0),
        RGB_COLOR(33, 47, 60),
        RGB_COLOR(120, 40, 31),
        RGB_COLOR(74, 35, 90),
        RGB_COLOR(27, 79, 114),
        RGB_COLOR(14, 98, 81),
        RGB_COLOR(125, 102, 8),
        RGB_COLOR(120, 66, 18),
        RGB_COLOR(110, 44, 0),
        RGB_COLOR(23, 32, 42)];
    });
    return colorArray;
}

-(CALayer *)selectedColorLayer{
    if (!_selectedColorLayer) {
        _selectedColorLayer = [CALayer new];
        _selectedColorLayer.cornerRadius = 4.0;
    }
    return _selectedColorLayer;
}

@end
